package com.caac.core.web.action.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caac.core.config.Config;
import com.caac.core.service.BaseManager;
import com.caac.core.service.NotFoundException;
import com.caac.core.service.UserManager;
import com.caac.core.web.action.BaseAction;
import com.caac.core.web.form.BaseForm;
import com.caac.core.web.form.UserForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class SaveUserAction extends BaseAction {

    protected ActionForward doExecute(ActionMapping mapping,
                                      BaseForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws
            Exception {
        UserForm uf = (UserForm) form;
//        String pId=uf.getPersonId();
//        String deptCode=uf.getUser().getUnitId();
//        BaseManager bm = this.getBaseManager();
        String[] id = request.getParameterValues("roleIds");
        UserManager um = this.getUserManager();
//        uf.getUser().setEmpId(uf.getPersonId());
        try {
            if (uf.getUser().getId() == null) {
                if (um.getUserByUsername(uf.getUser().getUsername()) != null) {
                    setSaveErrors(request, 1);
                    return mapping.getInputForward();
                }
                if (uf.getUser().getUsername() == null) {
                    setSaveErrors(request, 1);
                    return mapping.getInputForward();
                }

            }
        } catch (Exception e) {
        }

        try {

            um.saveUser(uf.getUser(), id,
                        this.getUserFromCache(request, response));
        } catch (NotFoundException ex) {
            setSaveErrors(request, 2);
            return mapping.getInputForward();
        }
        return this.forward(mapping);
    }

    private void setSaveErrors(HttpServletRequest request, int iErr) {
        ActionErrors errors = new ActionErrors();
        if (iErr == 1) {
            errors.add("userExist", new ActionError("errors.userExist"));
        } else if (iErr == 2) {
            errors.add("substation", new ActionError("errors.substation"));
        }
        this.saveErrors(request, errors);
    }
}
